import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';


import { LoginService } from '../../login/service/login.service';
import { HttpService } from '../../../share/http/http.service';
import { Message } from '../../../share/model/message.model';
import { Menu } from '../../../system/model/menu.model';

@Injectable()
export class MenuService {

    // 缓存用户的菜单数据
    menuData: Menu[] = null;

    // 头部菜单观察者,推送数据，通知
    public menuObserver = null;
    // 菜单缓存对象观察对象
    public menuObservable = new Observable<string>(observer => this.menuObserver = observer).share();

    changeMenuData(data: string) {
        this.menuObserver.next(data);
    }

    constructor(private httpService: HttpService, private loginService: LoginService) { }

    /**
     * 处理用户的菜单数据
     */
    init(): void {

        // 写死的数据
        // this.getMenuList();

        // 这里从后台数据库读取
        this.getMenuListByHttp();
    }

    private getMenuListByHttp() {
        this.httpService.httpGetCallback('menu/list', response => {
            let msg = response as Message;
            if (msg.errorCode === HttpService.SUCCESS) {
                this.menuData = this.createMenuTree(msg.data);
                // 默认选中
                this.setDefaultSelect();
                // 发射一个流表示点击了头部菜单
                this.changeMenuData('menu-service');
            } else {
                this.menuData = [];
            }
        });
    }

    private createMenuTree(data: any[]): Menu[] {
        console.log(data);
        if (data) {
            // 菜单数据
            let menus = this.getSortedMenu(data);
            // 最顶层的菜单数组
            let firstMenus = menus.filter(e => !e.pid);
            // 递归添加下级
            firstMenus.forEach(e => {
                this.addChildrenMenu(e, menus);
            });
            return firstMenus;
        }
        return [];
    }

    /**
     * 排序数组对象
     */
    private getSortedMenu(data: any[]): Menu[] {
        let menus: Menu[] = [];
        data.forEach(e => {
            let menu = new Menu();
            menu.setDataValue(e);
            menus.push(menu);
        });
        return menus.sort((a, b) => a.rank - b.rank);
    }

    /**
     * 递归添加孩子节点
     */
    private addChildrenMenu(parentMenu: Menu, menus: Menu[]) {
        menus.forEach(e => {
            if (parentMenu.id === e.pid) {
                parentMenu.children.push(e);
                this.addChildrenMenu(e, menus);
            }
        });
    }

    /**
     *  默认选中
     */
    private setDefaultSelect() {
        if (this.menuData[0]) {
            this.menuData[0].isChecked = true;
            if (this.menuData[0].children[0]) {
                this.menuData[0].children[0].isChecked = true;
            }
        }
    }


    private getMenuList() {
        let menuP = new Menu().init(['1', '', '', 'glyphicon glyphicon-cog', '平台'], []);
        menuP.children = [
            new Menu().init(['10', '1', '', 'glyphicon glyphicon-cog', '基本设置'], []),
            new Menu().init(['11', '1', '', 'glyphicon glyphicon-shopping-cart', '商品管理'], []),
            new Menu().init(['12', '1', '', 'glyphicon glyphicon-list-alt', '订单管理'], []),
            new Menu().init(['13', '1', '', 'glyphicon glyphicon-user', '人员管理'], []),
            new Menu().init(['13', '1', '', 'glyphicon glyphicon-cog', '售后服务'], [])
        ];
        menuP.children[0].children = [
            new Menu().init(['101', '10', '/main/setting', '', '配送费'], []),
            new Menu().init(['101', '10', '/main/banner/list', '', '首页轮播图'], ['/main/banner/edit/:id']),
            new Menu().init(['101', '10', '/main/news/list', '', '头条咨询'], ['/main/news/edit/:id']),
            new Menu().init(['101', '10', '/main/goods/vendor/local/list', '', '供销商本地商品'], ['/main/goods/vendor/local/edit/:id'])
        ];
        menuP.children[1].children = [
            new Menu().init(['111', '11', '/main/goods/pool/list', '', '商品池'], ['/main/goods/pool/edit/:id']),
            new Menu().init(['111', '11', '/main/goods/platform/list', '', '平台商品'], []),
            new Menu().init(['111', '11', '/main/goods/vendor/list', '', '供销商商品'], ['/main/goods/vendor/edit/:id']),
            new Menu().init(['111', '11', '/main/goods/landlord/list', '', '楼长商品'], ['/main/goods/landlord/edit/:id']),
            new Menu().init(['112', '11', '/main/rank/vendor/list', '', '竞价排名'], [])];
        menuP.children[2].children = [
            new Menu().init(['121', '12', '/main/order/vendor/buy/list', '', '供销商购买订单'], []),
            new Menu().init(['122', '12', '/main/order/buyer/list', '', '会员购买订单'], []),
            new Menu().init(['123', '12', '/main/order/withdraw/all/list/1', '', '供销商提现订单'], []),
            new Menu().init(['124', '12', '/main/order/withdraw/all/list/2', '', '楼长提现订单'], [])];
        menuP.children[3].children = [
            new Menu().init(['131', '13', '/main/user/platform/list', '', '平台'], ['/main/user/platform/edit/:id']),
            new Menu().init(['132', '13', '/main/user/vendor/list', '', '供销商'], ['/main/user/vendor/edit/:id']),
            new Menu().init(['133', '13', '/main/user/landlord/list', '', '楼长'], ['/main/user/landlord/edit/:id']),
            new Menu().init(['134', '13', '/main/user/buyer/list', '', '会员'], [])];
        menuP.children[4].children = [new Menu().init(['141', '14', '/main/complaint/list', '', '投诉建议'], [])];

        let menuV = new Menu().init(['2', '', '', 'glyphicon glyphicon-cog', '供销商'], []);
        menuV.children = [
            new Menu().init(['20', '2', '', 'glyphicon glyphicon-cog', '基本设置'], []),
            new Menu().init(['21', '2', '', 'glyphicon glyphicon-shopping-cart', '商品管理'], []),
            new Menu().init(['22', '2', '', 'glyphicon glyphicon-list-alt', '订单管理'], [])];
        menuV.children[0].children = [
            new Menu().init(['201', '20', '/main/setting', '', '配送费'], []),
            new Menu().init(['202', '20', '/main/local/goods/list', '', '提交本地商品'], ['/main/local/goods/edit/:id']),
            new Menu().init(['202', '20', '/main/local/goods/rank/list', '', '竞价排名'], [])];
        menuV.children[1].children = [
            new Menu().init(['211', '21', '/main/mygoods/vendor/list', '', '我的商品'], ['/main/mygoods/vendor/edit/:id']),
            new Menu().init(['212', '21', '/main/buygoods/vendor/list', '', '购买商品'], ['/main/buygoods/vendor/edit/:id'])];
        menuV.children[2].children = [
            new Menu().init(['221', '22', '/main/order/landlord/buy/list', '', '楼长购买订单'], []),
            new Menu().init(['222', '22', '/main/order/buyer/list', '', '会员购买订单'], []),
            new Menu().init(['223', '22', '/main/order/vendor/my/list', '', '我的购买订单'], []),
            new Menu().init(['224', '22', '/main/withdraw/list', '', '我的提现订单'], []),
            new Menu().init(['225', '22', '/main/order/buyer/vendor/landlord/count', '', '统计楼长销售'], [])];

        let menuL = new Menu().init(['3', '', '', 'glyphicon glyphicon-cog', '楼长'], []);
        menuL.children = [
            new Menu().init(['30', '3', '', 'glyphicon glyphicon-cog', '基本设置'], []),
            new Menu().init(['31', '3', '', 'glyphicon glyphicon-shopping-cart', '商品管理'], []),
            new Menu().init(['32', '3', '', 'glyphicon glyphicon-list-alt', '订单管理'], [])];
        menuL.children[0].children = [
            new Menu().init(['301', '30', '/main/setting', '', '配送费'], []),
            new Menu().init(['301', '30', '/main/landlord/my/qrcode', '', '我的二维码'], [])];
        menuL.children[1].children = [
            new Menu().init(['311', '31', '/main/mygoods/landlord/list', '', '我的商品'], ['/main/mygoods/landlord/edit/:id']),
            new Menu().init(['312', '31', '/main/buygoods/landlord/list', '', '购买商品'], ['/main/buygoods/landlord/edit/:id'])];
        menuL.children[2].children = [
            new Menu().init(['321', '32', '/main/order/landlord/my/list', '', '我的购买订单'], []),
            new Menu().init(['322', '32', '/main/order/buyer/list', '', '会员购买订单'], []),
            new Menu().init(['323', '32', '/main/withdraw/list', '', '我的提现订单'], [])];

        let menus: Menu[] = [];

        console.log(this.loginService.userInfo.accountType);

        switch (this.loginService.userInfo.accountType) {
            case 0:
                menus.push(menuP);
                break;
            case 1:
                menus.push(menuV);
                break;
            case 2:
                menus.push(menuL);
                break;
        }
        this.menuData = menus;
        console.log(this.menuData);
        // 默认选中
        this.setDefaultSelect();

        let subscription = this.menuObservable.subscribe(status => {
            subscription.unsubscribe();
        });

        // 发射一个流表示点击了头部菜单
        this.changeMenuData('menu-service');

    }

}

